// 游戏常量
const SUITS = ['hearts', 'diamonds', 'clubs', 'spades'];
const VALUES = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const SUIT_SYMBOLS = {
    'hearts': '♥️',
    'diamonds': '♦️',
    'clubs': '♣️',
    'spades': '♠️'
};
const BOSS_DATA = {
    'J': { health: 20, attack: 10 },
    'Q': { health: 30, attack: 15 },
    'K': { health: 40, attack: 20 }
};
const CARD_POINTS = {
    'A': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9,
    '10': 10,
    'J': 10,
    'Q': 15,
    'K': 20
};

// 游戏状态
let gameState = {
    playerCount: 1,
    currentPlayer: 1,
    handLimit: 8,
    deck: [],
    discardPile: [],
    players: [],
    currentBoss: null,
    bossHealth: 0,
    bossAttack: 0,
    selectedCards: [],
    playedCards: [],
    gamePhase: 'setup', // setup, play, discard, gameOver
    bosses: [],
    currentBossIndex: 0,
    jokerCount: 0,
    damageReduction: 0, // 用于记录黑桃技能减伤
    lastPassPlayer: 0, // 记录上一个过牌的玩家
    allPlayersPass: false, // 记录是否所有玩家都过牌
    jokerUsed: 0, // 记录单人模式下使用的Joker数量
    requiredDiscardPoints: 0 // 记录需要弃掉的点数总和
};

// DOM 元素
// const playerCountSelect = document.getElementById('player-count');
const startGameButton = document.getElementById('start-game');
const gameSetupDiv = document.querySelector('.game-setup');
const gameBoardDiv = document.querySelector('.game-board');
const gameOverDiv = document.querySelector('.game-over');
const playAgainButton = document.getElementById('play-again');
const playerHandDiv = document.getElementById('player-hand');
const playCardsButton = document.getElementById('play-cards');
const passTurnButton = document.getElementById('pass-turn');
const discardCardsButton = document.getElementById('discard-cards'); // 添加弃牌按钮引用
const bossNameElement = document.getElementById('boss-name');
const bossHealthElement = document.getElementById('boss-health');
const bossAttackElement = document.getElementById('boss-attack');
const deckCountElement = document.getElementById('deck-count');
const discardCountElement = document.getElementById('discard-count');
const playedCardsDiv = document.getElementById('played-cards');
const currentPlayerElement = document.getElementById('current-player');
const handLimitElement = document.getElementById('hand-limit');
const logContentDiv = document.getElementById('log-content');
const gameResultElement = document.getElementById('game-result');

// 事件监听器
startGameButton.addEventListener('click', startGame);
playAgainButton.addEventListener('click', resetGame);
playCardsButton.addEventListener('click', playSelectedCards);
passTurnButton.addEventListener('click', passTurn);
discardCardsButton.addEventListener('click', discardSelectedCards); // 添加弃牌按钮事件监听器

// 游戏初始化
function startGame() {
    // const playerCount = parseInt(playerCountSelect.value);
    const playerCount = 1;// 只支持单人游戏模式
    gameState.playerCount = playerCount;
    gameState.jokerUsed = 0; // 重置单人模式Joker使用数量
    
    // 设置手牌上限和Joker数量
    switch(playerCount) {
        case 1:
            gameState.handLimit = 8;
            gameState.jokerCount = 2; // 单人模式特殊规则
            break;
        case 2:
            gameState.handLimit = 7;
            gameState.jokerCount = 0;
            break;
        case 3:
            gameState.handLimit = 6;
            gameState.jokerCount = 1;
            break;
        case 4:
            gameState.handLimit = 5;
            gameState.jokerCount = 2;
            break;
    }
    
    // 初始化玩家
    gameState.players = [];
    for (let i = 0; i < playerCount; i++) {
        gameState.players.push({
            id: i + 1,
            hand: []
        });
    }
    
    // 创建并洗牌
    createDeck();
    shuffleDeck();
    
    // 设置Boss牌堆
    setupBossDeck();
    
    // 发牌
    dealCards();
    
    // 设置第一个Boss
    setupNextBoss();
    
    // 更新UI
    updateUI();
    
    // 切换到游戏界面
    gameSetupDiv.classList.add('hidden');
    gameBoardDiv.classList.remove('hidden');
    gameState.gamePhase = 'play';
    
    // 记录游戏开始
    logMessage('游戏开始！');
    logMessage(`Boss ${gameState.currentBoss} ${SUIT_SYMBOLS[gameState.currentBossSuit]} 出现了！生命值: ${gameState.bossHealth}, 攻击力: ${gameState.bossAttack}`);
}

// 创建卡组
function createDeck() {
    gameState.deck = [];
    
    // 添加普通牌 (1-10)
    for (const suit of SUITS) {
        for (let i = 0; i < 10; i++) {
            gameState.deck.push({
                suit: suit,
                value: VALUES[i],
                points: CARD_POINTS[VALUES[i]]
            });
        }
    }
    
    // 添加Joker
    for (let i = 0; i < gameState.jokerCount; i++) {
        gameState.deck.push({
            suit: 'joker',
            value: 'Joker',
            points: 0
        });
    }
}

// 设置Boss牌堆
function setupBossDeck() {
    // 按照J-Q-K顺序设置Boss，并分配花色
    gameState.bosses = [
        { value: 'J', suit: 'clubs' },    // J - 梅花
        { value: 'Q', suit: 'hearts' },   // Q - 红桃
        { value: 'K', suit: 'spades' }    // K - 黑桃
    ];
    gameState.currentBossIndex = 0;
}

// 洗牌
function shuffleDeck() {
    for (let i = gameState.deck.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [gameState.deck[i], gameState.deck[j]] = [gameState.deck[j], gameState.deck[i]];
    }
}

// 发牌
function dealCards() {
    for (const player of gameState.players) {
        while (player.hand.length < gameState.handLimit && gameState.deck.length > 0) {
            player.hand.push(gameState.deck.pop());
        }
    }
}

// 设置下一个Boss
function setupNextBoss() {
    if (gameState.currentBossIndex >= gameState.bosses.length) {
        endGame(true);
        return;
    }
    
    const boss = gameState.bosses[gameState.currentBossIndex];
    gameState.currentBoss = boss.value;
    gameState.currentBossSuit = boss.suit;
    gameState.bossHealth = BOSS_DATA[gameState.currentBoss].health;
    gameState.bossAttack = BOSS_DATA[gameState.currentBoss].attack;
    gameState.currentBossIndex++;
    gameState.damageReduction = 0; // 重置减伤
    gameState.lastPassPlayer = 0; // 重置过牌记录
    gameState.allPlayersPass = false; // 重置所有玩家过牌状态
}

// 更新UI
function updateUI() {
    // 更新Boss信息
    bossNameElement.textContent = `${gameState.currentBoss} ${SUIT_SYMBOLS[gameState.currentBossSuit]}`;
    bossHealthElement.textContent = gameState.bossHealth;
    bossAttackElement.textContent = Math.max(0, gameState.bossAttack - gameState.damageReduction);
    
    // 更新牌堆信息
    deckCountElement.textContent = gameState.deck.length;
    discardCountElement.textContent = gameState.discardPile.length;
    
    // 更新当前玩家信息
    currentPlayerElement.textContent = gameState.currentPlayer;
    handLimitElement.textContent = gameState.handLimit;
    
    // 更新玩家手牌
    renderPlayerHand();
    
    // 更新出牌区
    renderPlayedCards();
    
    // 根据游戏阶段更新按钮状态
    if (gameState.gamePhase === 'discard') {
        // 弃牌阶段：启用弃牌按钮，禁用其他按钮
        playCardsButton.classList.add('hidden');
        passTurnButton.classList.add('hidden');
        discardCardsButton.classList.remove('hidden');
        
        // 显示确认弃牌按钮
        discardCardsButton.disabled = false;
        discardCardsButton.textContent = '确认弃牌';
        
        // 添加弃牌提示
        addLog('请选择任意数量的牌（总和需≥' + gameState.requiredDiscardPoints + '）');
    }
    
    // 计算选中牌的总点数
    const currentPlayer = gameState.players[gameState.currentPlayer - 1];
    const selectedCards = gameState.selectedCards.map(index => currentPlayer.hand[index]);
    
    // 检查是否有Joker
    const hasJoker = selectedCards.some(card => card.value === 'Joker');
    
    if (hasJoker) {
        // 处理Joker逻辑
        handleJokerCard();
    } else {
        // 处理普通出牌逻辑
        handleNormalCards(selectedCards);
    }
    
    // 清空选中的牌
    gameState.selectedCards = [];
    
    // 检查游戏是否结束
    if (gameState.gamePhase === 'play') {
        // 更新UI，确保出牌区显示已出的牌
        updateUI();
        
        // 补牌
        drawCards();
        
        // 如果不是单人模式，切换到下一个玩家
        if (gameState.playerCount > 1 && !hasJoker) {
            nextPlayer();
        }
        
        // 再次更新UI
        updateUI();
    }
}

// 处理Joker牌
function handleJokerCard() {
    // 获取当前玩家手牌
    const currentPlayerHand = gameState.players[gameState.currentPlayer - 1].hand;
    
    // 找到Joker在手牌中的索引
    const jokerIndex = gameState.selectedCards[0];
    
    // 从手牌中移除Joker
    const jokerCard = currentPlayerHand.splice(jokerIndex, 1)[0];
    
    // 将Joker放入弃牌堆
    gameState.discardPile.push(jokerCard);
    
    // 记录使用Joker
    logMessage(`玩家${gameState.currentPlayer}使用了Joker！`);
    
    if (gameState.playerCount === 1) {
        // 单人模式特殊规则：重新抽牌
        gameState.jokerUsed++;
        
        // 将手牌放入弃牌堆
        while (currentPlayerHand.length > 0) {
            gameState.discardPile.push(currentPlayerHand.pop());
        }
        
        // 重新抽牌
        drawCards();
        
        logMessage('使用Joker重新抽牌！');
        
        // 如果使用了两张Joker，游戏结束
        if (gameState.jokerUsed >= 2) {
            logMessage('已使用两张Joker，游戏失败！');
            endGame(false);
        }
    } else {
        // 多人模式：破除Boss无效化能力，跳过伤害阶段，指定下一个玩家
        logMessage('Joker破除了Boss的无效化能力！');
        logMessage('跳过了伤害阶段！');
        
        // 重置所有玩家过牌状态
        gameState.allPlayersPass = false;
        gameState.lastPassPlayer = 0;
        
        // 提示选择下一个玩家（简化版：直接选择下一个玩家）
        nextPlayer();
        logMessage(`指定玩家${gameState.currentPlayer}进行下一步行动！`);
    }
}

// 处理普通牌
function handleNormalCards(selectedCards) {
    // 获取当前玩家手牌
    const currentPlayerHand = gameState.players[gameState.currentPlayer - 1].hand;
    
    // 计算总点数和收集花色
    let totalPoints = 0;
    const suits = new Set();
    
    // 记录出牌信息
    let cardInfo = '';
    
    // 从手牌中移除选中的牌，并计算总点数
    const playedCards = [];
    
    // 按照索引从大到小排序，以便从后往前移除（避免索引变化）
    const sortedIndices = [...gameState.selectedCards].sort((a, b) => b - a);
    
    for (const index of sortedIndices) {
        const card = currentPlayerHand.splice(index, 1)[0];
        playedCards.push(card);
        totalPoints += card.points;
        suits.add(card.suit);
        
        // 构建出牌信息
        cardInfo += `${card.value}${card.suit === 'joker' ? '🃏' : SUIT_SYMBOLS[card.suit]} `;
    }
    
    // 更新出牌区
    gameState.playedCards = playedCards;
    
    // 记录出牌
    logMessage(`玩家${gameState.currentPlayer}出牌: ${cardInfo}，总点数: ${totalPoints}`);
    
    // 重置所有玩家过牌状态
    gameState.allPlayersPass = false;
    gameState.lastPassPlayer = 0;
    
    // 激活花色技能
    activateSuitAbilities(playedCards, suits);
    
    // 对Boss造成伤害
    dealDamageToBoss(totalPoints);
    
    // 如果Boss还活着，玩家承受Boss伤害
    if (gameState.bossHealth > 0) {
        takeDamageFromBoss();
    }
    
    // 将出牌放入弃牌堆，但不立即清空出牌区，让UI可以显示出牌
    for (const card of playedCards) {
        gameState.discardPile.push(card);
    }
    
    // 不要立即清空出牌区，让UI可以显示出牌
    // gameState.playedCards = [];
}

// 激活花色技能
function activateSuitAbilities(playedCards, suits) {
    // 检查Boss是否会无效化某些花色技能
    const bossNullifiedSuit = gameState.currentBossSuit;
    
    // 处理每张牌的花色技能
    for (const card of playedCards) {
        // 跳过Joker
        if (card.suit === 'joker') continue;
        
        // 如果Boss无效化了这个花色，跳过
        if (card.suit === bossNullifiedSuit) {
            logMessage(`Boss ${gameState.currentBoss} (${SUIT_SYMBOLS[bossNullifiedSuit]}) 无效化了 ${SUIT_SYMBOLS[card.suit]} 的技能！`);
            continue;
        }
        
        // 根据花色激活技能
        switch (card.suit) {
            case 'hearts': // 红桃：从弃牌堆拿x张牌放入卡组底
                recoverCardsFromDiscard(card.points);
                break;
            case 'diamonds': // 方块：从卡组上方抽取x张牌
                drawExtraCards(card.points);
                break;
            case 'clubs': // 梅花：造成x双倍的伤害
                // 伤害加倍在dealDamageToBoss中处理
                logMessage(`梅花技能：造成${card.points}双倍的伤害！`);
                break;
            case 'spades': // 黑桃：减少敌人x点数的伤害
                gameState.damageReduction += card.points;
                logMessage(`黑桃技能：减少敌人${card.points}点伤害！当前减伤: ${gameState.damageReduction}`);
                break;
        }
    }
}

// 从弃牌堆恢复牌到卡组底部
function recoverCardsFromDiscard(count) {
    count = Math.min(count, gameState.discardPile.length);
    
    if (count <= 0) {
        logMessage('弃牌堆中没有牌可以恢复！');
        return;
    }
    
    // 从弃牌堆中随机选择count张牌
    const recoveredCards = [];
    for (let i = 0; i < count; i++) {
        const randomIndex = Math.floor(Math.random() * gameState.discardPile.length);
        const card = gameState.discardPile.splice(randomIndex, 1)[0];
        recoveredCards.push(card);
        gameState.deck.unshift(card); // 放入卡组底部
    }
    
    logMessage(`红桃技能：从弃牌堆恢复了${count}张牌到卡组底部！`);
}

// 额外抽牌
function drawExtraCards(count) {
    const currentPlayer = gameState.players[gameState.currentPlayer - 1];
    count = Math.min(count, gameState.deck.length);
    
    if (count <= 0) {
        logMessage('卡组中没有牌可以抽取！');
        return;
    }
    
    // 抽取额外的牌
    for (let i = 0; i < count; i++) {
        if (gameState.deck.length > 0) {
            currentPlayer.hand.push(gameState.deck.pop());
        }
    }
    
    logMessage(`方块技能：额外抽取了${count}张牌！`);
}

// 对Boss造成伤害
function dealDamageToBoss(damage) {
    // 检查是否有梅花牌，如果有则伤害翻倍
    const playedCards = gameState.playedCards;
    const hasClub = playedCards.some(card => card.suit === 'clubs');
    
    // 如果有梅花牌且Boss不会无效化梅花技能，伤害翻倍
    if (hasClub && gameState.currentBossSuit !== 'clubs') {
        // 计算梅花牌的点数总和
        const clubPoints = playedCards
            .filter(card => card.suit === 'clubs')
            .reduce((sum, card) => sum + card.points, 0);
        
        // 伤害加倍
        damage += clubPoints;
        logMessage(`梅花技能使伤害增加了${clubPoints}点！`);
    }
    
    // 对Boss造成伤害
    gameState.bossHealth -= damage;
    logMessage(`对Boss造成了${damage}点伤害！Boss剩余生命: ${Math.max(0, gameState.bossHealth)}`);
    
    // 检查Boss是否被击败
    if (gameState.bossHealth <= 0) {
        // 如果刚好将Boss血量减为0，则将Boss放入卡组顶部
        if (gameState.bossHealth === 0) {
            // 创建Boss牌
            const bossCard = {
                suit: gameState.currentBossSuit,
                value: gameState.currentBoss,
                points: CARD_POINTS[gameState.currentBoss]
            };
            
            // 将Boss牌放入卡组顶部
            gameState.deck.push(bossCard);
            logMessage(`Boss ${gameState.currentBoss} ${SUIT_SYMBOLS[gameState.currentBossSuit]} 被击败，放入卡组顶部！`);
        } else {
            logMessage(`Boss ${gameState.currentBoss} 被击败！`);
        }
        
        // 设置下一个Boss
        setupNextBoss();
    }
}

// 承受Boss伤害
function takeDamageFromBoss() {
    // 计算实际伤害（考虑黑桃减伤）
    const actualDamage = Math.max(0, gameState.bossAttack - gameState.damageReduction);
    
    if (actualDamage <= 0) {
        logMessage('黑桃技能完全抵消了Boss的伤害！');
        return;
    }
    
    logMessage(`Boss对玩家造成${actualDamage}点伤害！请选择要弃掉的牌，点数总和需大于等于${actualDamage}。`);
    
    // 设置游戏状态为弃牌阶段
    gameState.gamePhase = 'discard';
    gameState.requiredDiscardPoints = actualDamage;
    
    // 清空已选择的牌
    gameState.selectedCards = [];
    
    // 显示弃牌按钮，隐藏其他按钮
    playCardsButton.classList.add('hidden');
    passTurnButton.classList.add('hidden');
    discardCardsButton.classList.remove('hidden');
    
    // 更新UI
    updateUI();
}

// 处理玩家弃牌
function discardSelectedCards() {
    const actualDamage = gameState.requiredDiscardPoints;
    const currentPlayer = gameState.players[gameState.currentPlayer - 1];
    
    // 计算选中牌的总点数
    let totalPoints = 0;
    const selectedCards = gameState.selectedCards.map(index => {
        const card = currentPlayer.hand[index];
        totalPoints += card.points;
        return card;
    });
    
    // 检查点数是否足够
    if (totalPoints < actualDamage) {
        logMessage(`选择的牌点数总和为${totalPoints}，不足以抵挡Boss的${actualDamage}点伤害！`);
        return;
    }
    
    // 按照索引从大到小排序，以便从后往前移除（避免索引变化）
    const sortedIndices = [...gameState.selectedCards].sort((a, b) => b - a);
    
    // 弃掉选中的牌
    const discardedCards = [];
    
    for (const index of sortedIndices) {
        const discardedCard = currentPlayer.hand.splice(index, 1)[0];
        discardedCards.push(discardedCard);
        gameState.discardPile.push(discardedCard);
    }
    
    // 构建弃牌信息
    let discardInfo = '';
    for (const card of discardedCards.reverse()) { // 反转以显示原始顺序
        discardInfo += `${card.value}${card.suit === 'joker' ? '🃏' : SUIT_SYMBOLS[card.suit]} `;
    }
    
    logMessage(`玩家${gameState.currentPlayer}弃掉了 ${discardInfo}(总点数: ${totalPoints}) 来抵挡Boss的伤害。`);
    
    // 恢复游戏状态
    gameState.gamePhase = 'play';
    gameState.selectedCards = [];
    
    // 恢复按钮状态
    playCardsButton.classList.remove('hidden');
    passTurnButton.classList.remove('hidden');
    discardCardsButton.classList.add('hidden');
    
    // 更新UI
    updateUI();
    
    // 补牌
    drawCards();
    
    // 如果不是单人模式，切换到下一个玩家
    if (gameState.playerCount > 1) {
        nextPlayer();
    }
}

// 补牌
function drawCards() {
    const currentPlayer = gameState.players[gameState.currentPlayer - 1];
    
    // 补牌至手牌上限
    while (currentPlayer.hand.length < gameState.handLimit && gameState.deck.length > 0) {
        currentPlayer.hand.push(gameState.deck.pop());
    }
    
    // 如果牌库已空，检查是否需要洗牌
    if (gameState.deck.length === 0 && gameState.discardPile.length > 0) {
        // 将弃牌堆洗入牌库
        gameState.deck = [...gameState.discardPile];
        gameState.discardPile = [];
        shuffleDeck();
        logMessage('牌库已空，将弃牌堆洗入牌库！');
    }
}

// 过牌
function passTurn() {
    // 单人模式不能过牌
    if (gameState.playerCount === 1) {
        return;
    }
    
    // 记录当前玩家过牌
    logMessage(`玩家${gameState.currentPlayer}选择过牌。`);
    
    // 记录上一个过牌的玩家
    gameState.lastPassPlayer = gameState.currentPlayer;
    
    // 切换到下一个玩家
    nextPlayer();
    
    // 检查是否所有玩家都过牌了
    if (gameState.lastPassPlayer === gameState.currentPlayer) {
        gameState.allPlayersPass = true;
        logMessage('所有玩家都选择过牌，弃掉出牌区的牌！');
        
        // 将出牌区的牌放入弃牌堆
        for (const card of gameState.playedCards) {
            gameState.discardPile.push(card);
        }
        
        // 不要立即清空出牌区，让UI可以显示出牌
        // gameState.playedCards = [];
    }
    
    // 更新UI
    updateUI();
}

// 切换到下一个玩家
function nextPlayer() {
    gameState.currentPlayer = gameState.currentPlayer % gameState.playerCount + 1;
    logMessage(`轮到玩家${gameState.currentPlayer}的回合。`);
}

// 游戏结束
function endGame(isWin) {
    gameState.gamePhase = 'gameOver';
    
    // 显示游戏结果
    if (isWin) {
        gameResultElement.textContent = '恭喜你！成功击败了所有Boss！';
        logMessage('游戏胜利！成功击败了所有Boss！');
    } else {
        gameResultElement.textContent = '游戏失败！Boss击败了你！';
        logMessage('游戏失败！Boss击败了你！');
    }
    
    // 显示游戏结束界面
    gameBoardDiv.classList.add('hidden');
    gameOverDiv.classList.remove('hidden');
}

// 重置游戏
function resetGame() {
    // 隐藏游戏结束界面
    gameOverDiv.classList.add('hidden');
    
    // 显示游戏设置界面
    gameSetupDiv.classList.remove('hidden');
    
    // 清空日志
    logContentDiv.innerHTML = '';
    
    // 重置游戏状态
    gameState = {
        playerCount: 1,
        currentPlayer: 1,
        handLimit: 8,
        deck: [],
        discardPile: [],
        players: [],
        currentBoss: null,
        bossHealth: 0,
        bossAttack: 0,
        selectedCards: [],
        playedCards: [],
        gamePhase: 'setup',
        bosses: [],
        currentBossIndex: 0,
        jokerCount: 0,
        damageReduction: 0,
        lastPassPlayer: 0,
        allPlayersPass: false,
        jokerUsed: 0
    };
}